package com.crawData.service.impl.douyin;

import com.crawData.service.CrawDataLoginManagerService;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.stereotype.Service;

import java.util.HashMap;

import static com.crawData.utility.WebDriverUtility.getWebDriver;

/*
 * 数据爬取抖音登录管理
 */

@Service
@Slf4j
public class CrawDataLoginDouYinManagerServiceImpl implements CrawDataLoginManagerService {

    @Override
    public String login(HashMap<String,String> parms) {
        //获取要爬取的抖音主页地址
        String url = parms.get("url");
        if ("".equals(url)) {
            return "请输入要爬取的抖音主页地址";
        }
        //获取手机号
        String phone = parms.get("phone");
        //实例化浏览器驱动
        WebDriver webDriver = getWebDriver(url+phone);
        try {
            //使用while循环等待扫码登录成功！
            loginOption(webDriver);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }


    /**
     *登录抖音-扫码登录-等待用户扫码
     * @param driver
     */
    private  void loginOption(WebDriver driver) throws InterruptedException {
        driver.get("https://www.douyin.com/");
        //  需要要睡眠6秒等待登录页面弹出
        Thread.sleep(30*100);
        //登录标签
        boolean loginFlag=true;
        log.info("开始扫码登录！");
        while (loginFlag) {

            try {
                //获取扫码状态
                WebElement element = driver.findElement(By.xpath("//*[@id=\"web-login-container\"]/article/article/article/div[2]/div/div[1]/div[2]/div/div/p[2]"));
                String text = element.getText();
                if (text.equals("登录成功")){
                    //停止等待扫码（登录成功！）
                    loginFlag=false;
                }
            }catch (Exception e){
                log.error("扫码失败{}",e);
            }

        }
        log.info("扫码登录成功！");

    }

}
